﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Security.Principal;
using ScrumTime.Services;
using ScrumTime.Models;

namespace ScrumTime.Helpers
{
    public class SessionHelper
    {
        public static string CURRENTPRODUCTID = "currentProductId";
        public static string CURRENTSPRINTID = "currentSprintId";
        public static string LASTMAINTABSELECTED = "lastMainTabSelected";

        public static string CURRENTUSERGUID = "currentUserGuid";

        public static string ISUSER_ADMIN = "ISUSER_ADMIN";

        public static bool GetIsUserAdmin()
        {
            
            bool resultado = false;
            String value = String.Empty;

            if (HttpContext.Current.Session[ISUSER_ADMIN] != null)
            {
                value = HttpContext.Current.Session[ISUSER_ADMIN].ToString();
            }

            if ( ! String.IsNullOrEmpty(value))
            {
                resultado = bool.Parse(value);
            }

            return resultado;
        }

        public static void SetIsUserAdmin( HttpSessionStateBase session, bool value)
        {
            session[ISUSER_ADMIN] = value;
        }

        public static void SetUserGuid(HttpSessionStateBase session, String user_guid)
        {
            session[CURRENTUSERGUID] = user_guid;
        }


        public static String GetUserGuid(HttpSessionStateBase session)
        {
            String resultado = String.Empty;
            if (session[CURRENTUSERGUID] != null)
            {
                resultado = session[CURRENTUSERGUID].ToString();
            }
            else {
                UserService userservice = new UserService();
                session[CURRENTUSERGUID] = userservice.GetGuiByName(HttpContext.Current.User.Identity.Name);
                resultado = session[CURRENTUSERGUID].ToString();                
            }
            return resultado;
        }

        public static int GetCurrentProductId(string username, HttpSessionStateBase session)
        {
            var value = session[CURRENTPRODUCTID];
            if (value == null || int.Parse(value.ToString()) == -1 )
            {
                session[CURRENTPRODUCTID] = -1;
                value = -1;
                if (Helpers.SessionHelper.GetIsUserAdmin())
                {
                    ScrumTimeEntities scrumTimeEntities = new ScrumTimeEntities();
                    if (scrumTimeEntities.Products.Count() > 0)
                    {
                        value = scrumTimeEntities.Products.First<Product>().ProductId;
                        session[CURRENTPRODUCTID] = value;
                    }                    
                }
                else {
                    ScrumTime.Services.UserService userService = new ScrumTime.Services.UserService();
                    ScrumTime.Models.User user = userService.GetUserByGUI(ScrumTime.Helpers.SessionHelper.GetUserGuid(session));
                    if (user.Products.Count > 0)
                    {
                        value = user.Products.ElementAt(0).ProductId;
                        session[CURRENTPRODUCTID] = value;
                    }                    
                }
            }
            return (int)value;
        }


        public static int GetCurrentProductId(System.Web.SessionState.HttpSessionState session)
        {
            var value = session[CURRENTPRODUCTID];
            if (value == null)
            {
                    value = -1;
            }
            return (int)value;
        }

        public static int GetCurrentProductId(System.Web.HttpSessionStateBase session)
        {
            var value = session[CURRENTPRODUCTID];
            if (value == null)
            {
                value = -1;
            }
            return (int)value;
        }


        public static void SetCurrentProductId(string username, HttpSessionStateBase session, int value)
        {
            SaveUserSetting(username, CURRENTPRODUCTID, value);
            session[CURRENTPRODUCTID] = value;
        }

        public static void SetCurrentProductId(string username, System.Web.SessionState.HttpSessionState session, int value)
        {
            SaveUserSetting(username, CURRENTPRODUCTID, value);
            session[CURRENTPRODUCTID] = value;
        }


        public static int GetCurrentSprintId(string username, HttpSessionStateBase session)
        {
            var value = session[CURRENTSPRINTID];
            if (value == null)
            {                
                    value = -1;
            }
            return (int)value;
        }

        public static int GetCurrentSprintId(string username, System.Web.SessionState.HttpSessionState session)
        {
            var value = session[CURRENTSPRINTID];
            if (value == null)
            {                
                    value = -1;
            }
            return (int)value;
        }

        

        public static void SetCurrentSprintId(string username, HttpSessionStateBase session, int value)
        {
            SaveUserSetting(username, CURRENTSPRINTID, value);
            session[CURRENTSPRINTID] = value;
        }

        public static int GetLastSelectedMainTabIndex(string username, HttpSessionStateBase session)
        {
            var value = session[LASTMAINTABSELECTED];
            if (value == null)
            {
                // check the db
                ScrumTimeEntities scrumTimeEntities = new ScrumTimeEntities();
                UserSetting userSetting = LoadUserSetting(scrumTimeEntities, username);
                if (userSetting != null && userSetting.LastMainTabSelected != null)
                {
                    session[LASTMAINTABSELECTED] = userSetting.LastMainTabSelected;
                    value = userSetting.LastMainTabSelected;
                }
                else
                    value = -1;
            }
            return (int)value;
        }

        public static void SetLastSelectedMainTabIndex(string username, HttpSessionStateBase session, int value)
        {
            SaveUserSetting(username, LASTMAINTABSELECTED, value);
            session[LASTMAINTABSELECTED] = value;
        }

        private static UserSetting LoadUserSetting(ScrumTimeEntities scrumTimeEntities, string username)
        {
            UserSetting userSetting = null;
            if (username != null && username.Length > 0)
            {
                userSetting = UserSettingService.GetUserSettingByUsername(scrumTimeEntities, username);
            }
            return userSetting;
        }

        private static void SaveUserSetting(string username, string settingName, object value)
        {
            //if (value != null && username != null && username.Length > 0)
            //{
            //    ScrumTimeEntities scrumTimeEntities = new ScrumTimeEntities();
            //    UserSetting existingUserSetting = LoadUserSetting(scrumTimeEntities, username);
            //    if (settingName == CURRENTPRODUCTID)
            //        existingUserSetting.CurrentProduct = (int)value;
            //    else if (settingName == CURRENTSPRINTID)
            //        existingUserSetting.CurrentSprint = (int)value;
            //    else if (settingName == LASTMAINTABSELECTED)
            //        existingUserSetting.LastMainTabSelected = (int)value;
            //    scrumTimeEntities.SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);
            //}
            //else
            //    throw new Exception("Failed to save the user settings for setting: " + settingName);
        }

        public static void CreateFirstTimeDefaults(string username)
        {
            ScrumTimeEntities scrumTimeEntities = new ScrumTimeEntities();
            UserSetting userSetting = UserSettingService.GetUserSettingByUsername(scrumTimeEntities, username);
            if (userSetting == null)
            {
                // Load sample product id
                ProductService productService = new ProductService(scrumTimeEntities);
                int productIdOfSample = productService.GetProductIdOfSample();
                if (productIdOfSample > -1)
                {
                    SprintService sprintService = new SprintService(scrumTimeEntities);
                    List<Sprint> mostRecentSprints = sprintService.GetMostRecentSprints(productIdOfSample, -1, 1);
                    if (mostRecentSprints.Count > 0 && mostRecentSprints[0] != null)
                    {
                        userSetting = new UserSetting()
                        {
                            CurrentProduct = productIdOfSample,
                            CurrentSprint = mostRecentSprints[0].SprintId,
                            LastMainTabSelected = 1,
                            Username = username
                        };
                        scrumTimeEntities.AddToUserSettings(userSetting);
                        scrumTimeEntities.SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);
                    }
                    
                }                
            }
        }
    }
}